<template>
  <el-dialog title="新增电价方案" width="900px" :model-value="modelValue" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="方案名称" prop="schemeName">
            <el-input v-model="formValue.schemeName" placeholder="请输入方案名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生效时间" prop="executeTime">
            <el-date-picker
              v-model="formValue.executeTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择生效时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formValue.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="配置项" prop="priceItemList" label-position="top">
            <el-row align="middle" v-for="(item, index) in formValue.priceItemList" :key="index" :gutter="20" class="item-row">
              <el-col :span="5">
                <div class="item-form__item">
                  <div class="form__label">时段类型：</div>
                  <div class="form__value">
                    <el-select v-model="item.type" filterable>
                      <el-option v-for="option in bandEnum" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                  </div>
                </div>
              </el-col>
              <el-col :span="5">
                <div class="item-form__item">
                  <div class="form__label">价格：</div>
                  <div class="form__value">
                    <el-input v-model="item.price" type="number" placeholder="价格" />
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="item-form__item">
                  <div class="form__label">开始时间：</div>
                  <div class="form__value">
                    <el-time-select v-model="item.startTime" start="00:00" end="23:00" :max-time="item.endTime" />
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="item-form__item">
                  <div class="form__label">结束时间：</div>
                  <div class="form__value">
                    <el-time-select
                      v-model="item.endTime"
                      start="00:00"
                      end="23:59"
                      include-end-time
                      :min-time="item.startTime"
                    />
                  </div>
                </div>
              </el-col>
              <el-col :span="2">
                <el-tooltip v-if="index === formValue.priceItemList.length - 1" placement="top" content="新增">
                  <el-icon class="item-from__icon" color="#409eff" @click="commEvent.onAdd"><Plus /></el-icon>
                </el-tooltip>
                <el-tooltip v-if="formValue.priceItemList.length > 1" placement="top" content="删除">
                  <el-icon class="item-from__icon" color="#f56c6c" @click="commEvent.onDelete(index)"><CloseBold /></el-icon>
                </el-tooltip>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { bandEnum } from "@/utils/enum"
import { addElectricPrice } from "@/api/modules/parameter"
import type { SystemSpace } from "@/api/interface/parameter"

interface Props {
  modelValue: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
// 表单数据
const formValue = ref({
  schemeName: "",
  executeTime: "",
  remark: "",
  priceItemList: [{ type: 1, price: "", startTime: "", endTime: "" }] as SystemSpace.SaveElectricPrice["priceItemList"]
})
//  表单校验
const validPriceiItem = (_rule: any, value: any[], callback: any) => {
  if (value.some(item => !item.price || !item.startTime || !item.endTime)) {
    callback("请将配置项补充完整")
    return
  }
  callback()
}
const rules: FormRules = {
  schemeName: [{ required: true, message: "请填写方案名称", trigger: "blur" }],
  executeTime: [{ required: true, message: "请选择生效时间", trigger: "change" }],
  priceItemList: [{ required: true, validator: validPriceiItem, trigger: "blur" }]
}

// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 新增配置项
  onAdd: () => {
    const _item = { type: 1, price: "", startTime: "", endTime: "" }
    formValue.value.priceItemList = [...formValue.value.priceItemList, _item]
  },
  // 新增配置项
  onDelete: (index: number) => {
    formValue.value.priceItemList.splice(index, 1)
  },
  // 提交
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const params: SystemSpace.SaveElectricPrice = {
        ...formValue.value,
        priceItemList: formValue.value.priceItemList.map(item => ({
          ...item,
          price: Number(item.price)
        }))
      }
      const { code } = await addElectricPrice(params)
      if (code !== "200") return
      ElMessage.success("新增成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  val => {
    if (val) {
      nextTick(() => {
        if (!formRef.value) return
        formRef.value.resetFields()
        formValue.value.priceItemList = [{ type: 1, price: "", startTime: "", endTime: "" }]
      })
    }
  }
)
</script>

<style lang="scss" scoped>
.item-row {
  width: 100%;
  margin-bottom: 15px;
  .item-form__item {
    display: flex;
    align-items: center;
    width: 100%;
    .form__label {
      flex-shrink: 0;
      font-size: 13px;
    }
    .form__value {
      flex: 1;
    }
  }
  .item-from__icon {
    margin-left: 5px;
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
